define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'ykjp/purchase/storage/index' + location.search,
                    add_url: 'ykjp/purchase/storage/add',
                    edit_url: 'ykjp/purchase/storage/edit',
                    detail_url: "ykjp/purchase/storage/detail",
                    del_url: 'ykjp/purchase/storage/del',
                    multi_url: 'ykjp/purchase/storage/multi',
                    table: 'ykjp_storage',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true, formatter: function (value, row, index) {
                                if (row.status == 0) {
                                    return {
                                        disabled: false,
                                    };
                                } else {
                                    return {
                                        disabled: true,
                                    }

                                }
                            }},
                        {field: 'code', title: __('Code')},
                        {field: 'supplier.name', title: __('Supplier.name')},
                        {field: 'contact', title: __('Contact')},
                        {field: 'phone', title: __('Phone')},
                        {field: 'delivery_time', title: __('Delivery_time'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime, datetimeFormat: "YYYY-MM-DD"},
                        {field: 'the_way', title: __('The_way'), searchList: {"2": __('The_way 2'), "1": __('The_way 1'), "0": __('The_way 0')}, formatter: Table.api.formatter.normal},
                        {field: 'status', title: __('Status'), searchList: {"2": __('Status 2'), "1": __('Status 1'), "0": __('Status 0'), "3": __('Status 3')}, formatter: Table.api.formatter.status},
                        {field: 'inbound_type', title: __('Inbound_type'), visible: false, searchList: {"1": __('Inbound 1'), "0": __('Inbound 0')}, formatter: Table.api.formatter.inbound_type},
                        {field: 'remark', title: __('Remark')},
                        {field: 'billing_time', title: __('Billing_time'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime, datetimeFormat: "YYYY-MM-DD"},
                        {field: 'updatetime', title: __('Updatetime'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime, datetimeFormat: "YYYY-MM-DD"},
                        {field: 'operate',
                            title: __('Operate'),
                            table: table, events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'addtabs',
                                    title: __('look'),
                                    classname: 'btn btn-xs btn-primary  btn-addtabs',
                                    icon: 'fa fa-pencil-square-o',
                                    url: $.fn.bootstrapTable.defaults.extend.detail_url,
                                }
                            ],
                            formatter: Table.api.formatter.operate,
                            formatter: function (value, row, index) {
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true);
                                if (row.status == 3) {
                                    $(table).data("operate-del", null);
                                }
                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'ykjp/purchase/storage/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'ykjp/purchase/storage/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'ykjp/purchase/storage/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {

            $('#myModal').on('show.bs.modal', function (e) {
                Controller.supplier();
            });
            $('#myModal').on('hidden.bs.modal', function () {
                $('#table1').bootstrapTable('destroy');
            });

            $('#modelPurchase').on('hidden.bs.modal', function () {
                $('#table3').bootstrapTable('destroy');
            });
            $('#modelPurchase').on('show.bs.modal', function (e) {
                Controller.product();
            });

            $('#modelProduct').on('show.bs.modal', function (e) {

                var btn = $(e.relatedTarget)
                console.log(btn)
                Controller.getProduct(btn);
            });

            $('#modelProduct').on('show.bs.modal', function (e) {

                var btn = $(e.relatedTarget)
                Controller.getProduct(btn);
            });

            $('#modelProduct').on('hidden.bs.modal', function () {
                $('#table2').bootstrapTable('destroy');
            });
            // $("#c-purchase").on('click',function(e){
            //     var id= $("#c-supId").val();
            //     console.log(id)
            //     if(id>0){
            //        $('#modelPurchase').modal('show');
            //     }else{
            //        Layer.alert( __('Please select a supplier'));
            //     }
            // })
            $("#c-purchase").focus(function (e) {
                var id = $("#c-supId").val();
                console.log(id)
                if (id > 0) {
                    $('#modelPurchase').modal('show');
                } else {
                    Layer.alert(__('Please select a supplier'));
                }
            })
            $('#c-supplier').focus(function () {
                $('#myModal').modal('show');
            });
            //          $(".find").focus(function () {
            //     $("#modelProduct").modal("show");
            // });
            setnums();
            Controller.api.bindevent();
        },
        edit: function () {
            $('#modelProduct').on('show.bs.modal', function (e) {
                var btn = $(e.relatedTarget)
                Controller.getProduct(btn);
            });

            $('#modelProduct').on('hidden.bs.modal', function () {
                $('#table2').bootstrapTable('destroy');
            });
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }, supplier: function () {
            Table.api.init({
                extend: {
                    index_url: 'ykjp/purchase/storage/getSupPro?obj=1'
                }
            });

            var table = $("#table1");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,
                columns: [
                    [
                        {field: 'name', title: __('Name')},
                        {field: 'contact', title: __('Contact')},
                        {field: 'phone', title: __('Phone')},
                        {field: 'description', title: __('Description')},
                        {
                            field: 'operate',
                            width: "120px",
                            title: __('Selected'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'ajax',
                                    text: __('Selected'),
                                    title: __('Selected'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-magic',
                                    url: 'ykjp/purchase/storage/getSupPro?obj=3',
                                    success: function (data, ret) {
                                        $("#c-supplier").val(data.row.name);
                                        $("#c-supId").val(data.row.id);
                                        $("#c-contact").val(data.row.contact);
                                        $("#c-phone").val(data.row.phone);
                                        $("#c-address").val(data.row.address);
                                        $("#c-city").citypicker("reset");
                                        if (data.city != "") {

                                            $("#c-city").citypicker("destroy");
                                            $("#c-city").citypicker({
                                                province: data.city[0],
                                                city: data.city[1],
                                                district: data.city[2]
                                            });

                                            // $("#tt").append('<select  class="second form-control"  data-url="purchase/addorder/getWarehouse" data-query-name="pid" style="width: 100%"> <option value="2" selected="">001</option> </select>');

                                        }
                                        $('#myModal').modal('hide');
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                },
                            ],
                            formatter: Table.api.formatter.buttons
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        product: function () {
            Table.api.init({
                extend: {
                    index_url: 'ykjp/purchase/storage/add?obj=3'
                }
            });

            var table = $("#table3");
            var id = $("#c-supId").val();
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url + "&supid=" + id,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,

                columns: [
                    [
                        {field: 'code', title: __('Code')},
                        {field: 'contact', title: __('Contact')},
                        {field: 'phone', title: __('Phone')},
                        {field: 'description', title: __('Description')},
                        {
                            field: 'operate',
                            width: "120px",
                            title: __('Selected'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'ajax',
                                    text: __('Selected'),
                                    title: __('Selected'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-magic',
                                    url: 'ykjp/purchase/storage/add?obj=4',
                                    success: function (data, ret) {
                                        $("#table tbody tr").not(':eq(0)').not(':last').remove();
                                        $("#c-purchase").val(data.code.code);
                                        $("#c-code").val(data.code.code);
                                        $("#c-pur").val(data.code.id);
                                        $("#inbound").val(0);
                                        $("#inbound").attr("disabled", "disabled");

                                        var strs = "";
                                        if (data.product != "") {
                                            for (var i = 0; i < data.product.length; i++) {
                                                if (i == 0) {
                                                    var product = data.product[i];
                                                    var _this = $('#table tbody tr:eq(0)');
                                                    _this.find(".find").val(product.products.name);
                                                    _this.find(".find").attr("data-id", product.product_id);
                                                    _this.find(".find").attr("data-pro-id", product.id);
                                                    _this.find(".unit").text(product.unit);
                                                    _this.find("td:eq(1)").text(product.products.sku);
                                                    _this.find("td:eq(3)").text(product.specification);
                                                    _this.find(".nums").val(product.wait_nums);
                                                    _this.find(".wait_nums").val(product.wait_nums);
                                                    _this.find(".unit-price").val(product.price);
                                                    _this.find(".subtotal").text(product.subtotal);
                                                    _this.find(".remarks").text(product.remarks);
                                                    if (product.products.prop != "") {
                                                        var arr = JSON.parse(product.products.prop);
                                                        var str = "";
                                                        for (var j = 0; j < arr.length; j++) {
                                                            if (typeof (arr[j]['value']) != "undefined" && arr[j]['value'] !== null) {
                                                                str += arr[j]['title'] + ":" + arr[j]['value'] + "; <br>";
                                                            }
                                                        }
                                                    }
                                                    _this.find("td:eq(4)").html(str);
                                                } else {
                                                    strs += rows(data.product[i], data.code.warehouse_partition_id);
                                                }
                                            }
                                        }
                                        if (strs != "") {
                                            $('#table tbody tr:eq(0)').after(strs);
                                        }
                                        $("#hose-fist").val(data.code.warehouse_id);
                                        $("#c-type").val(data.code.type);
                                        $("#money").val(data.code.money);
                                        $("#allMoney").text(data.code.money);
                                        $("#totalMoney").text(data.code.totalMoney);
                                        $("#totalMoneys").val(data.code.totalMoney);
                                        $("#allNums").val(data.code.totalNums);
                                        $(".totalnums").text(data.code.totalNums);
                                        $("#c-rate").val(data.code.rate);
                                        $(".second option").remove();
                                        $(".second").removeAttr("disabled");

                                        if (data.row == "") {
                                            $(".second").attr("disabled", "disabled");
                                        } else {
                                            var str = '<option value="" >请选择</option>';
                                            for (var i = 0; i < data.row.length; i++) {
                                                var op = "";
                                                if (data.code.warehouse_partition_id != "" && data.code.warehouse_partition_id == data.row[i].value) {
                                                    op = '<option value="' + data.row[i].value + '" selected="selected">' + data.row[i].name + '</option>';
                                                } else {
                                                    op = '<option value="' + data.row[i].value + '" >' + data.row[i].name + '</option>';
                                                }
                                                str += op;
                                            }
                                            $(".second").append(str);

                                        }
                                        setnums();
                                        totalNums(null);
                                        calTotalMoneys();
                                        Form.api.bindevent($("form#cxselectform"));
                                        // console.log($("#money").val())
                                        alldisabled()
                                        $('#modelPurchase').modal('hide');

                                        // $('#modelPurchase').modal('hide');
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                        $(".second").val(data.code.warehouse_partition_id);
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                },
                            ],
                            formatter: Table.api.formatter.buttons
                        }
                    ]
                ]
            });

            // 为表格绑定事件

            Table.api.bindevent(table);

        }, getProduct: function (btn) {
            Table.api.init({
                extend: {
                    index_url: 'ykjp/purchase/storage/getSupPro?obj=2'
                }
            });

            var table = $("#table2");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,
                escape: false,
                columns: [
                    [
                        {field: 'name', title: __('Name')},
                        {field: 'specification', title: __('Specification')},
                        {field: 'sku', title: __('Sku')},
                        {field: 'prop', title: __('Prop'), formatter: function (value, row, index) {
                                var str = "";
                                if (row.prop != "") {
                                    var arr = JSON.parse(row.prop);
                                    console.log(arr[0]);

                                    for (var i = 0; i < arr.length; i++) {

                                        if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                                            str += arr[i]['title'] + ":" + arr[i]['value'] + ";<br>";
                                        }
                                    }
                                }
                                return str;
                            }},
                        {
                            field: 'operate',
                            width: "120px",
                            title: __('Selected'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'ajax',
                                    text: __('Selected'),
                                    title: __('Selected'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-magic',
                                    url: 'ykjp/purchase/storage/getSupPro?obj=4',
                                    success: function (data, ret) {
                                        var _this = btn.parent().parent();
                                        _this.find(".find").val(data.row.name);
                                        _this.find(".find").attr("data-id", data.row.id);
                                        _this.find(".unit").text(data.row.unit);
                                        _this.find("td:eq(1)").text(data.row.sku);
                                        _this.find("td:eq(3)").text(data.row.specification);
                                        if (data.row.prop != "") {
                                            var arr = JSON.parse(data.row.prop);
                                            var str = "";
                                            for (var i = 0; i < arr.length; i++) {
                                                if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                                                    str += arr[i]['title'] + ":" + arr[i]['value'] + "; <br>";
                                                }
                                            }
                                            _this.find("td:eq(4)").html(str);
                                        }
                                        $('#modelProduct').modal('hide');
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                },
                            ],
                            formatter: Table.api.formatter.buttons
                        }
                    ]
                ]
            });
            Table.api.bindevent(table);

        }
    };
    return Controller;
});

// 添加
function addRow() {
    var len = $('#table tr').length - 1;
    var lens = len - 2;
    var tempTr = '<tr>' +
            '<td class="prid" data-pro-id="" data-id="">' + len + '</td>' +
            '<td></td>' +
            '<td><input data-pro-id=""  data-id="" type="text" name="" class="find" data-toggle="modal" data-target="#modelProduct" data-rule=""></td>' +
            '<td></td>' +
            '<td></td>' +
            '<td class="unit"></td>' +
            //         ' <td> <select  class="second form-control"  name="row[warehouse_partition_id]" data-url="purchase/addorder/getWarehouse" data-query-name="pid" style="width: 100%">'+
            // '<option value="2" selected="">001</option>'+
            //  '</select></td>'+
            '<td><input  type="number" name="" disabled="disabled" class="wait_nums" value="0" readonly="readonly" style="" ></td>' +
            '<td><input  type="number" name="" data-rule="required;integer;range(0~);" class="nums" onblur="totalNums(this)"></td>' +
            '<td><input  type="number" data-rule="required;range(0~);" name="" onblur="calMoney(this)"  class="unit-price"></td>' +
            '<td class="subtotal"></td>' +
            '<td><textarea rows="2" class="remarks" cols="20"></textarea></td>' +
            '<td> <button type="button" class="btn btn-primary adds" onclick="addRow()">添加</button><button type="button" class="btn del  btn-default" onclick="delRow(this)" >删除</button> </td>' +
            '</tr>';
    $('#table tbody tr:eq(' + lens + ')').after(tempTr);
    //         $(".find").focus(function () {
    //     $("#modelProduct").modal("show");
    // });
}

//设置序号
function setnums() {
    var len = $('#table tr').length;
    for (var i = 1; i < len - 1; i++) {
        $('#table tr:eq(' + i + ') td:first').text(i);
    }
}

function rows(obj, vs) {
    var str = "";
    if (obj.products.prop != "") {
        var arr = JSON.parse(obj.products.prop);

        for (var i = 0; i < arr.length; i++) {
            if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                str += arr[i]['title'] + ":" + arr[i]['value'] + "; ";
            }
        }
    }
    var tempTr = '<tr>' +
            '<td></td>' +
            '<td>' + obj.products.sku + '</td>' +
            '<td><input data-pro-id="' + obj.id + '" data-id="' + obj.product_id + '" value="' + obj.products.name + '" type="text" name="" class="find" data-toggle="modal" data-target="#modelProduct" data-rule=""></td>' +
            '<td>' + obj.products.specification + '</td>' +
            '<td>' + str + '</td>' +
            '<td class="unit">' + obj.unit + '</td>' +
            //         ' <td> <select  class="second form-control"  data-url="purchase/addorder/getWarehouse" data-query-name="pid" style="width: 100%">'+
            // '<option value="'+vs+'" selected="selected">001</option>'+
            //  '</select></td>'+
            '<td><input  type="number" name="" disabled="disabled"  class="wait_nums" value="' + obj.wait_nums + '" readonly="readonly" style="" ></td>' +
            '<td><input  type="number" name="" value="' + obj.wait_nums + '" data-rule="required;integer;range(0~);" class="nums" onblur="totalNums(this)"></td>' +
            '<td><input  type="number" value="' + obj.price + '" data-rule="required;" name="" onblur="calMoney(this)"  class="unit-price"></td>' +
            '<td class="subtotal">' + obj.subtotal + '</td>' +
            '<td><textarea rows="2" class="remarks" cols="20">' + obj.remarks + '</textarea></td>' +
            '<td> <button type="button" class="btn btn-primary adds" onclick="addRow()">添加</button><button type="button" class="btn del btn-default" onclick="delRow(this)" >删除</button> </td>' +
            '</tr>';
    return tempTr;
}

//计算总数量
function totalNums(obj) {
    var len = $('#table tr').length;
    var total = 0;
    if (obj != null) {
        calMoney(obj);
    }
    for (var i = 1; i < len - 1; i++) {
        var nums = $('#table tr:eq(' + i + ') .nums').val();
        if (nums == "") {
            nums = 0;
        } else {
            nums = getNumValue(nums);
            if (nums == false || nums < 0) {
                total = false;
                return false;
            }
        }
        total += nums;
    }
    if (total != false) {
        $(".totalnums").text(total);
        $("#allNums").val(total);
    }
}


function getNumValue(num) {
    if (!isNaN(num) && num != "") {
        num = parseFloat(num);
        var a = isPositiveInteger(num)
        if (a == false) {
            num = false;
        }
    } else {
        num = false;
    }
    return num;
}

function isInteger(obj) {
    return obj % 1 === 0
}

function isPositiveInteger(s) {//是否为正整数
    var re = /^[0-9]+$/;
    return re.test(s)
}
// 小计
function calMoney(obj) {
    var total = 0;
    var nums = $(obj).parent().parent().find(".nums").val();
    var nuitprice = $(obj).parent().parent().find(".unit-price").val();
    if (nuitprice == "") {
        return false;
    }
    nuitprice = parseFloat(nuitprice);
    nums = getNumValue(nums);
    if (nums == false) {
        return false;
    }
    total = nuitprice * nums;
    total = total.toFixed(2);
    $(obj).parent().parent().find(".subtotal").text(total);
    calTotalMoneys();
}
// 计算总金额
function calTotalMoneys() {
    var len = $('#table tr').length;
    var total = 0;
    for (var b = 1; b < len - 1; b++) {
        var str = '#table tr:eq(' + b + ') .subtotal';
        var a = $(str).text();
        if (a == "") {
            a = 0;
        }
        a = parseFloat(a);
        if (a == "NaN" || a == "" || a == undefined) {
            a = 0;
        }
        total += a;
    }
    $("#table #allMoney").text(total);
    var rate = $("#c-rate").val();
    rate = parseFloat(rate);
    var totalMoney = total * (1 + rate / 100);
    $("#money").val(total);
    totalMoney = totalMoney.toFixed(2);
    $("#totalMoney").text(totalMoney);
    $("#totalMoneys").val(totalMoney);

}

// 删除
function delRow(obj) {
    var pur = $("#c-pur").val();
    //  alert(pur)
    // if(pur!=""||){
    //  return false;
    // }

    // console.log($('#table tbody tr').length)
    if ($('#table tbody tr').length == 2) {
        alert(__("Can't delete"));
        return false;
    }
    $(obj).parent().parent().remove();
    totalNums(null);
    calTotalMoneys()
    setnums();
}

function submitData() {
    var data = $("#add-form").serialize();
    // console.log(data)
    if ($("#c-supId").val() == '') {
        Toastr.error(__("Please select a merchant"));
        return false;
    }
    if ($("#hose-fist").val() == 0) {
        Toastr.error(__("Please select a warehouse"));
        return false;
    }
    $('#add-form').isValid(function (v) {
        // console.log(v)
        if (v == true) {
            var len = $("#table tr").length;
            var arr = new Array();
            var arrtep = new Array();
            var c = [];
            for (var i = 1; i < len - 1; i++) {
                var id = $("#table tr:eq(" + i + ")").find('.find').attr("data-id");
                var proid = $("#table tr:eq(" + i + ")").find('.find').attr("data-pro-id");
                if (id == "") {
                    Toastr.error(__("Please select a product"));
                    return false;
                }
                var second = $(".second").val();
                var nums = $("#table tr:eq(" + i + ")").find('.nums').val();
                var unitPrice = $("#table tr:eq(" + i + ")").find('.unit-price').val();
                var subtotal = $("#table tr:eq(" + i + ")").find('.subtotal').text();
                var unit = $("#table tr:eq(" + i + ")").find('.unit').text();
                var remarks = $("#table tr:eq(" + i + ")").find('.remarks').val();
                var b = i - 1;
                arr.push({"product_id": id, "price": unitPrice, "nums": nums, "subtotal": subtotal, "unit": unit, "remark": remarks, "partition_id": second, "purchase_proid": proid});
            }
            var temp = JSON.stringify(arr);
            resutlData = data + "&" + "product=" + temp;
            Fast.api.ajax({
                url: 'ykjp/purchase/storage/add?obj=5',
                data: resutlData
            }, function (data, ret) {
                //成功的回调
                if (data.result = "success") {

                    layer.msg('成功提交', {
                        time: 2000, //2s后自动关闭
                        end: function () {
                            location.href = "index";
                        }
                    });
                }
                // console.log(data);
                // return false;
            }, function (data, ret) {
                //失败的回调
                alert(ret.msg);
                return false;
            });
        }
    })

}

// 禁用标签
function alldisabled() {
    $(".del").attr("disabled", "disabled");
    $(".adds").attr("disabled", "disabled");
    $('#table tbody tr .find').attr("disabled", "disabled");
}


function submitUpdate(obj) {
    var data = $("#add-form").serialize();
    // console.log(data)
    if ($("#c-supId").val() == '') {
        Toastr.error(__("Please select a merchant"));
        return false;
    }
    if ($("#hose-fist").val() == 0) {
        Toastr.error(__("Please select a warehouse"));
        return false;
    }
    $('#add-form').isValid(function (v) {
        // console.log(v)
        if (v == true) {
            var len = $("#table tr").length;
            var arr = new Array();
            var arrtep = new Array();
            var c = [];
            for (var i = 1; i < len - 1; i++) {
                var id = $("#table tr:eq(" + i + ")").find('.find').attr("data-id");
                var proid = $("#table tr:eq(" + i + ")").find('.find').attr("data-pro-id");
                if (id == "") {
                    Toastr.error(__("Please select a product"));
                    return false;
                }
                var second = $(".second").val();
                var nums = $("#table tr:eq(" + i + ")").find('.nums').val();
                var wait_nums = $("#table tr:eq(" + i + ")").find('.wait_nums').val();
                var unitPrice = $("#table tr:eq(" + i + ")").find('.unit-price').val();
                var subtotal = $("#table tr:eq(" + i + ")").find('.subtotal').text();
                var unit = $("#table tr:eq(" + i + ")").find('.unit').text();
                var remarks = $("#table tr:eq(" + i + ")").find('.remarks').val();
                var data_id = $("#table tr:eq(" + i + ")").find('.prid').attr("data-id");
                var data_pro = $("#table tr:eq(" + i + ")").find('.prid').attr("data-pro-id");
                var b = i - 1;
                console.log(data_pro);
                if (data_pro != "" && data_pro > 0) {
                    // if(wait_nums<nums){
                    //    Toastr.error(__("The number of warehousing cannot be greater"));
                    //    return false;
                    // }
                }
                arr.push({"product_id": id, "price": unitPrice, "nums": nums, "subtotal": subtotal, "unit": unit, "remark": remarks, "partition_id": second, "purchase_proid": proid, "data_id": data_id, "purchase_proid": data_pro});
            }
            var temp = JSON.stringify(arr);
            resutlData = data + "&" + "product=" + temp;
            Fast.api.ajax({
                url: 'ykjp/purchase/storage/updateData?ids=' + obj,
                data: resutlData
            }, function (data, ret) {
                //成功的回调

                if (data.result = "success") {

                    layer.msg('成功提交', {
                        time: 2000, //2s后自动关闭
                        end: function () {
                            location.reload();
                        }
                    });
                }
                // console.log(data);
                // return false;
            }, function (data, ret) {
                //失败的回调
                Layer.alert(ret.msg);
                return false;
            });
        }
    })

}


function approval(obj, id) {
    Fast.api.ajax({
        url: "ykjp/purchase/sto_audit/approval?ids=" + id,
        data: {"type": obj}
    }, function (data, ret) {
        //成功的回调
        if (data.result = "success") {
            layer.msg('成功提交', {
                time: 2000, //2s后自动关闭
                end: function () {
                    location.reload();
                }
            });
        }
    }, function (data, ret) {
        alert(ret.msg);
        return false;
    });
}

function storage(id) {
    Fast.api.ajax({
        url: "ykjp/purchase/storage/inventory?ids=" + id,
    }, function (data, ret) {
        //成功的回调
        if (data.result = "success") {
            layer.msg('入库成功', {
                time: 2000, //2s后自动关闭
                end: function () {
                    location.reload();
                }
            });
        }
    }, function (data, ret) {
        alert(ret.msg);
        return false;
    });
}

function Anti(id) {
    Fast.api.ajax({
        url: "ykjp/purchase/storage/Anti?ids=" + id,
    }, function (data, ret) {
        //成功的回调
        if (data.result = "success") {
            location.reload();
        }
    }, function (data, ret) {
        alert(ret.msg);
        return false;
    });
}




function appWhy(id) {
    var str = "<div  style='width:80%;margin-left:auto;margin-right:auto'><textarea class='reason' rows='3' cols='38'></textarea></div>";
    Layer.open({
        title: __('Please fill in the reason'), //页面标题
        content: str,
        area: ['400px', '230px'], //自定义文本域宽高
        btn: ['确定', '取消'],
        yes: function (e, value) {
            var reason = $(".reason").val().trim();
            if (reason == "") {
                alert(__("Reason cannot be empty"));
            } else {
                apprNo(reason, id);
            }
        }, btn2: function () {
            return 0;
        }
    })
}


function apprNo(why, id) {
    Fast.api.ajax({
        url: "ykjp/purchase/sto_audit/approval?ids=" + id,
        data: {"type": "no", "reason": why}
    }, function (data, ret) {
        //成功的回调

        if (data.result = "success") {

            layer.msg('成功提交', {
                time: 2000, //2s后自动关闭
                end: function () {
                    location.reload();
                }
            });
        }
    }, function (data, ret) {
        Layer.alert(ret.msg);
        return false;
    });
}

function printPdf() {
    var headerText = $(".panel-heading").text();
    $(".panel-heading").text("入库单").css({
        "width":"200px",
        "margin":"0 auto",
        "font-size":"50px",
    });
    $(".prindBody .print-row,.prindBody .code label,.prindBody .code div").removeClass("col-xs-12").css({"float":"left"});
    $(".prindBody .print-row").removeClass("col-xs-12").addClass("col-xs-6").css({"float":"left"});
    $(".prindBody .print-row div , .prindBody .print-row label,.prindBody .print-remark div,.prindBody .print-remark label").removeClass("col-xs-12").css({"float":"left"});
    $(".print-total .print-total-row .print-row").removeClass("col-xs-12").css({"float":"right","width":"30%","margin-right":"-10%"});
    $(".print-total-row .print-row div,.print-total-row .print-row label").removeClass("col-xs-12");

    $("#ribbon").css('display','none');
    $(".no-print").css('display','none');
    window.print();

    $(".prindBody .print-row,.prindBody .code label,.prindBody .print-row,.prindBody .code div").addClass("col-xs-12").removeAttr("style");
    $(".prindBody .print-row").removeClass("col-xs-6").addClass("col-xs-12").removeAttr("left");
    $(".prindBody .print-row div , .prindBody .print-row label,.prindBody .print-remark div,.prindBody .print-remark label").addClass("col-xs-12").removeAttr("style");

    $(".print-total .print-total-row .print-row").addClass("col-xs-12").removeAttr("style");
    $(".print-total-row .print-row label,.print-total-row .print-row div").addClass("col-xs-12").removeAttr("style");;
    $(".no-print").css('display','block');
    $("#ribbon").css('display','block');
    $(".panel-heading").text(headerText).removeAttr("style");
}




